/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Cadastro.java
 *
 * Created on 30/04/2011, 11:04:25
 */
package cliente.gui;

import java.awt.Component;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JLayeredPane;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import util.ProtocoloMensagem;
import util.Email;
import util.VerificaLogin;

/**
 *
 * @author cleiton
 */
public class Cadastro extends javax.swing.JFrame {

    private ProtocoloMensagem protocoloMensagem;
    
    private String hostname;
    private int porta;
    

    /** Creates new form Cadastro */
    public Cadastro(String hostname, int porta) {
        this.hostname = hostname;
        this.porta = porta;
        
        protocoloMensagem = new ProtocoloMensagem();
        initComponents();
          try {
             // if(!UIManager.getLookAndFeel().getName().contains("Nimbus"))
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        pfConfirmarSenha = new javax.swing.JPasswordField();
        pfSenha = new javax.swing.JPasswordField();
        tfMatricula = new javax.swing.JTextField();
        tfNome = new javax.swing.JTextField();
        tfEmail = new javax.swing.JTextField();
        tfConfirmarEmail = new javax.swing.JTextField();
        btEnviar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Usuário");
        setResizable(false);

        jLabel1.setText("Matricula");

        jLabel2.setText("Nome:");

        jLabel3.setText("Email:");

        jLabel4.setText("Confirmar Email:");

        jLabel5.setText("Senha");

        jLabel6.setText("Confirmar Senha");

        pfConfirmarSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pfConfirmarSenhaActionPerformed(evt);
            }
        });

        tfEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfEmailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel6)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfConfirmarEmail)
                            .addComponent(tfMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tfNome, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
                            .addComponent(tfEmail)
                            .addComponent(pfConfirmarSenha)
                            .addComponent(pfSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(tfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tfConfirmarEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(pfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(pfConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btEnviar.setText("Enviar Solicitação de Cadastro");
        btEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEnviarActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel7.setText("Cadastro de Usuário");
        jLabel7.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(66, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(181, Short.MAX_VALUE)
                .addComponent(btEnviar)
                .addGap(108, 108, 108))
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addComponent(jLabel7)
                .addContainerGap(153, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btEnviar)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfEmailActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfEmailActionPerformed

    private void btEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEnviarActionPerformed

        ProtocoloMensagem cdm = new ProtocoloMensagem();
        String[] mensagemFromServer;
        JLayeredPane jLayeredPane = (JLayeredPane) this.getRootPane().getComponent(1);
        JPanel jPanel = (JPanel) jLayeredPane.getComponent(0);
        jPanel = (JPanel) jPanel.getComponent(0);
        if (isCamposPreenchidoCorreto(jPanel)) {
            String mensagem = cdm.codificarCadastroUsuario(tfMatricula.getText(), VerificaLogin.gerarMD5(pfSenha.getText()), tfEmail.getText(), tfNome.getText());

            try {
                Socket clientSocket = new Socket(hostname,porta);
                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                DataInputStream inFromServidor = new DataInputStream(clientSocket.getInputStream());
                outToServer.writeUTF(mensagem);
                mensagemFromServer = protocoloMensagem.decodificar(inFromServidor.readUTF());
                JOptionPane.showMessageDialog(this, mensagemFromServer[1]);
                if(mensagemFromServer[0].equals("SUCE"))
                limparCampos(jPanel);
                else{
                    if(mensagemFromServer[0].equals("ERRO")){
                    if(mensagemFromServer[1].equals("Erro: Matricula informada ja esta em uso \n"
                        + "Caso voce ja fez o cadastro, aguarde ate \n"
                        + "que o administrador aceite sua solicitacao"))
                    tfMatricula.setText("");}

                }

            } catch (UnknownHostException e) {

                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }//GEN-LAST:event_btEnviarActionPerformed

    private void pfConfirmarSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pfConfirmarSenhaActionPerformed
        btEnviarActionPerformed(evt);        // TODO add your handling code here:
    }//GEN-LAST:event_pfConfirmarSenhaActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new Cadastro().setVisible(true);
//            }
//        });
//    }

    private void limparCampos(JPanel jPanel) {
        Component component[] = jPanel.getComponents();
        for (int i = 0; i < component.length; i++) {
            if (component[i] instanceof JPasswordField) {
                JPasswordField jpSenha = (JPasswordField) component[i];
                jpSenha.setText("");
            } else {
                if (component[i] instanceof JTextField) {
                    JTextField auxText = (JTextField) component[i];
                    auxText.setText("");
                }
            }
        }


    }

    private boolean isCamposPreenchidoCorreto(JPanel jPanel) {
        if (isCampoPreenchido(jPanel1)) {
            if (isEmailigual()) {
                if (isSenhaIgual(pfSenha.getText(), pfConfirmarSenha.getText())) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean isCampoPreenchido(JPanel jpanel) {
        Component component[] = jpanel.getComponents();

        for (int i = 0; i < component.length; i++) {
            if (component[i] instanceof JPasswordField) {
                JPasswordField jpSenha = (JPasswordField) component[i];
                if (jpSenha.getText().equals("")) {
                    JOptionPane.showInputDialog("Preencha Todos as Senha");
                    return false;
                }
            } else {
                if (component[i] instanceof JTextField) {
                    JTextField auxText = (JTextField) component[i];
                    if (auxText.getText().equals("")) {
                        //TODO Mudar so os JoptPanel
                        JOptionPane.showInputDialog("Preencha Todos os Campos");
                        return false;
                    }

                }
            }
        }
        return true;
    }

    /**Verifica se email e email de Confirmação são iguais e Validos*/
    private boolean isEmailigual() {

        if (tfConfirmarEmail.getText().equals(tfEmail.getText())) {
            if (Email.isEmailValido(tfEmail.getText().toString())) {
                return true;
            } else {
                JOptionPane.showMessageDialog(null, "E-mail Inválido!");
            }
        } else {
            JOptionPane.showInputDialog("Email não iguais");
        }
        return false;
    }

    private boolean isSenhaIgual(String senha, String senhaComparar) {

        if (VerificaLogin.isSenhaIgual(senha, senhaComparar)) {
            return true;
        } else {
            pfConfirmarSenha.setText("");
            pfSenha.setText("");
            return false;
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btEnviar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPasswordField pfConfirmarSenha;
    private javax.swing.JPasswordField pfSenha;
    private javax.swing.JTextField tfConfirmarEmail;
    private javax.swing.JTextField tfEmail;
    private javax.swing.JTextField tfMatricula;
    private javax.swing.JTextField tfNome;
    // End of variables declaration//GEN-END:variables
}
